package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Product;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.FavoriteService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏夹控制器
 */
@Slf4j
@RestController
@RequestMapping("/favorite")
@Tag(name = "收藏夹模块")
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private UserService userService;

    @Operation(summary = "添加商品到收藏")
    @PostMapping("/add")
    public Result<?> addFavorite(@RequestBody AddFavoriteRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            if (request.getProductId() == null) {
                return Result.error("商品ID不能为空");
            }

            boolean success = favoriteService.addFavorite(user.getId(), request.getProductId());
            return success ? Result.success("收藏成功") : Result.error("收藏失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("添加收藏失败", e);
            return Result.error("收藏失败: " + e.getMessage());
        }
    }

    @Operation(summary = "取消收藏")
    @DeleteMapping("/{id}")
    public Result<?> removeFavorite(@Parameter(description = "收藏ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = favoriteService.removeFavorite(id, user.getId());
            return success ? Result.success("取消收藏成功") : Result.error("取消收藏失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("取消收藏失败", e);
            return Result.error("取消收藏失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取收藏列表")
    @GetMapping("/list")
    public Result<List<Product>> getFavoriteList() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            List<Product> favoriteList = favoriteService.getFavoriteList(user.getId());
            return Result.success("查询成功", favoriteList);
        } catch (Exception e) {
            log.error("获取收藏列表失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "检查是否已收藏")
    @GetMapping("/check/{productId}")
    public Result<Map<String, Boolean>> checkFavorite(
            @Parameter(description = "商品ID") @PathVariable Long productId) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean isFavorite = favoriteService.checkFavorite(user.getId(), productId);
            Map<String, Boolean> result = new HashMap<>();
            result.put("isFavorite", isFavorite);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("检查收藏状态失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Data
    public static class AddFavoriteRequest {
        private Long productId;
    }
}
